﻿using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 方块基类
/// </summary>
public class TileBase : MonoBehaviour
{
    // 自身类型
    public TileType tileType;
    // 自身生成类型
    public TileCreateType createType;
    // 自身状态
    public TileState TileState
    {
        get => tileState;
        set
        {
            tileState = value;
            if (value == TileState.Disable)
            {
                button.enabled = true;
                button.interactable = false;
                boxCollider.enabled = true;
            }
            else if (value == TileState.Normal)
            {
                button.enabled = true;
                button.interactable = true;
                boxCollider.enabled = true;
            }
            else
            {
                boxCollider.enabled = false;
                button.enabled = false;
            }
        }
    }
    [SerializeField]
    private TileState tileState;
    // 自身所在层
    public int tileLayer = 1;
    // 自身位置
    public Vector2 tilePosition;
    public Vector2 originalPos;
    // 范围内对象
    public List<TileBase> tileInScope;

    // 自身控件
    private Button button;
    private BoxCollider2D boxCollider;


    private void Awake()
    {
        button = GetComponent<Button>();
        boxCollider = GetComponent<BoxCollider2D>();
    }

    /// <summary>
    /// 方块初始化
    /// </summary>
    public void TileInit()
    {
        TileState = TileState.Disable;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.GetComponent<TileBase>().TileState == TileState.Suspend
            || collision.GetComponent<TileBase>().TileState == TileState.Purging
            || TileState == TileState.Suspend || TileState == TileState.Purging)
            return;

        if (!tileInScope.Contains(collision.GetComponent<TileBase>()) && collision.GetComponent<TileBase>().tileLayer > tileLayer)
            tileInScope.Add(collision.GetComponent<TileBase>());
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (TileState == TileState.Disable || TileState == TileState.Normal)
        {
            if (tileInScope.Contains(collision.GetComponent<TileBase>()) && collision.GetComponent<TileBase>().tileLayer > tileLayer)
                tileInScope.Remove(collision.GetComponent<TileBase>());
        }
    }

    private void LateUpdate()
    {

        if (TileState == TileState.Suspend || TileState == TileState.Purging)
            return;
        if (GameUIManager.Instance.isGameOver)
            return;

        if (tileInScope.Count > 0 && TileState != TileState.Disable)
            TileState = TileState.Disable;
        else if (tileInScope.Count == 0 && TileState != TileState.Normal)
            TileState = TileState.Normal;
    }


    /// <summary>
    /// 方块选择点击
    /// </summary>
    public void TileClicked()
    {
        if (TileState == TileState.Disable || TileState == TileState.Suspend || TileState == TileState.Purging)
            return;
        if (TilesBarManager.Instance.suspendTiles.Count >= 7)
            return;

        AudioManager.Instance.PlayButtonSound();
        // 方块移动至底栏
        SetOriginalPos();
        Vector2 newPos = TilesBarManager.Instance.GetTilePosInBar(this);
        TileState = TileState.Suspend;
        TilesBarManager.Instance.AddTileOnBar(this);
        TilesBarManager.Instance.TileMoveOnBar();
        transform.DOMove(newPos, 0.5f).SetEase(Ease.OutExpo).OnComplete(() =>
        {
            TilesBarManager.Instance.TilesBarCheck(this);
        });
    }

    /// <summary>
    /// 方块在底栏上的移动
    /// </summary>
    public void TileMove()
    {
        if (transform.position != TilesBarManager.Instance.tilePos[TilesBarManager.Instance.suspendTiles.IndexOf(this)].position)
        {
            transform.DOMove(TilesBarManager.Instance.tilePos[TilesBarManager.Instance.suspendTiles.IndexOf(this)].position, 0.4f).SetEase(Ease.Linear);
        }
    }

    /// <summary>
    /// 方块清除
    /// </summary>
    public void TilePurging()
    {
        AudioManager.Instance.PlayCancleSound();
        DOTween.To(() => transform.localScale, x => transform.localScale = x, new Vector3(0, 0, 1), 0.4f).SetEase(Ease.InBack).OnComplete(() =>
        {
            Destroy(gameObject);
            // 胜利判断
            if (TileManager.Instance.levelTiles.Count <= 0)
            {
                Debug.Log("胜利");
                if (!GameUIManager.Instance.isGameOver)
                    GameUIManager.Instance.ShowGameWinPanel();
            }
        });
    }

    /// <summary>
    /// 记录方块自身位置信息
    /// </summary>
    public void SetOriginalPos()
    {
        originalPos = this.transform.position;
    }

    /// <summary>
    /// 方块撤销
    /// </summary>
    public void TileCancle()
    {
        Debug.Log("方块撤销");
        TileState = TileState.Normal;
        TileManager.Instance.levelTiles.Add(this);
        TilesBarManager.Instance.suspendTiles.Remove(this);
        TilesBarManager.Instance.OperationTiles.Remove(this);
        TilesBarManager.Instance.suspendType[tileType] -= 1;
        transform.SetParent(TileManager.Instance.tilesParent);
        transform.DOMove(originalPos, 0.5f).SetEase(Ease.OutExpo).OnComplete(() =>
        {
            Debug.Log("撤销完成");
            TilesBarManager.Instance.TileMoveOnBar();
        });
    }

    /// <summary>
    /// 方块重新洗牌
    /// </summary>
    public void TileReshuffle(Vector2 pos, int layer, int index)
    {
        TileState = TileState.Suspend;
        tileInScope.Clear();
        transform.SetSiblingIndex(index);
        transform.DOMove(pos, 0.25f).SetEase(Ease.Linear).OnComplete(() =>
        {
            tileLayer = layer;
            TileState = TileState.Disable;
        });
    }

    /// <summary>
    /// 方块提示移动
    /// </summary>
    public void TileHintMove()
    {
        SetOriginalPos();
        Vector2 newPos = TilesBarManager.Instance.GetTilePosInBar(this);
        TileState = TileState.Suspend;
        TilesBarManager.Instance.AddTileOnBar(this);
        TilesBarManager.Instance.TileMoveOnBar();
        transform.DOMove(newPos, 0.5f).SetEase(Ease.OutExpo).SetUpdate(true).OnComplete(() =>
        {
            Debug.Log("清除检测");
            TilesBarManager.Instance.TilesBarCheck(this);
        });
    }


}

/// <summary>
/// 方块类型
/// </summary>
public enum TileType
{
    Tile_1,
    Tile_2,
    Tile_3,
    Tile_4,
    Tile_5,
    Tile_6,
    Tile_7,
    Tile_8,
    Tile_9,
    Tile_10,
    Tile_11,
    Tile_12,
    Tile_13,
    Tile_14,
    Tile_15,
    Tile_16,
    Tile_17,
    Tile_18,
    Tile_19,
    Tile_20
}

/// <summary>
/// 方块状态：正常、禁用、挂起、清除
/// </summary>
public enum TileState
{
    Normal,
    Disable,
    Suspend,
    Purging
}
